package leetcode.editor.cn;

import java.util.Arrays;
import java.util.HashMap;

/**
题目名字---:只出现一次的数字
题目编号---:136	
解题时间---:2021-12-03 07:37:07
*/

public class SingleNumber{
    public static void main(String[] args) {
        Solution solution = new SingleNumber().new Solution();
        singleNumber2(new int[]{4,1,2,1,2});
    }

    /**
     * 使用HashMap计数
     * @param nums
     * @return
     */
    public static int singleNumber(int[] nums) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i : nums) {
            if (hashMap.containsKey(i)) {
                hashMap.put(i,hashMap.get(i)+1);
            }else {
                hashMap.put(i,1);
            }
        }
        int res = 0;
        for (Integer integer : hashMap.keySet()) {
            if (hashMap.get(integer)==1) {
                res = integer;
                break;
            }
        }
        return res;
    }
    public static int singleNumber2(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0,j=1; j < nums.length; i+=2,j+=2) {
            if (nums[i]!=nums[j])
                return nums[i];
        }
        return nums[nums.length-1];
    }
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int singleNumber(int[] nums) {
        int single = 0;
        for (int num : nums) {
            single ^= num;
        }
        return single;
    }
}
//leetcode submit region end(Prohibit modification and deletion)


}